package com.ww.learn.coroutine.context

import kotlinx.coroutines.*

val threadLocal = ThreadLocal<String?>()

// 打印结果
//pre-main, current thread: Thread[#1,main,5,main], thread local value: 'main'
//Launch start, current thread: Thread[#21,DefaultDispatcher-worker-1,5,main], thread local value: 'launch'
//After yield, current thread: Thread[#21,DefaultDispatcher-worker-1,5,main], thread local value: 'launch'
//Post-main, current thread: Thread[#1,main,5,main], thread local value: 'main'
fun main() = runBlocking<Unit> {
    threadLocal.set("main")
    println("pre-main, current thread: ${Thread.currentThread()}, thread local value: '${threadLocal.get()}'")
    val job = launch(Dispatchers.Default + threadLocal.asContextElement(value = "launch")) {
        println("Launch start, current thread: ${Thread.currentThread()}, thread local value: '${threadLocal.get()}'")
        yield()
        println("After yield, current thread: ${Thread.currentThread()}, thread local value: '${threadLocal.get()}'")
    }
    job.join()
    println("Post-main, current thread: ${Thread.currentThread()}, thread local value: '${threadLocal.get()}'")
}